package com.yuanxin.chooseimage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.yuanxin.chooseimage.customutil.LocalUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

/**
 * Created by lemon on 2016/10/25.
 */

public class ReadImageDataManager extends ReactContextBaseJavaModule {
    public ReadImageDataManager(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    /**
     * @return the name of this module. This will be the name used to {@code require()} this module
     * from javascript.
     */
    @Override
    public String getName() {
        return "ReadImageDataManager";
    }

    @ReactMethod
    public void readImages(final ReadableArray fileArray, final Promise promise) {
        try {
            ImageBaseTask imageBaseTask = new ImageBaseTask(promise);
            imageBaseTask.execute(fileArray);
        } catch (Exception ex) {
            promise.reject("error", ex.getMessage());
        }
    }

    @ReactMethod
    public void readImage(final ReadableMap fileInfo, final Promise promise) {
        try {
            String filePath = fileInfo.getString("filePath");
            double imageWidth = -1;
            double imageHeight = -1;
            int scale = -1;
            if (fileInfo.hasKey("width"))
                imageWidth = fileInfo.getDouble("width");
            if (fileInfo.hasKey("height"))
                imageWidth = fileInfo.getDouble("height");
            if (fileInfo.hasKey("scale"))
                scale = (int) fileInfo.getDouble("scale") * 100;
            WritableMap baseFile = Arguments.createMap();
            baseFile.putString("filePath", filePath);
            baseFile.putString("imageData", LocalUtil.getPirBase(filePath, imageWidth, imageHeight, scale));
            promise.resolve(baseFile);
        } catch (Exception ex) {
            promise.reject("error", ex.getMessage());
        }
    }

}

class FileInfoBean {
    private String filePath;
    private int scale;
    private int width;
    private int height;

    public String getObjectKey() {
        return objectKey;
    }

    public void setObjectKey(String objectKey) {
        this.objectKey = objectKey;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public int getScale() {
        return scale;
    }

    public void setScale(int scale) {
        this.scale = scale;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    private String objectKey;
}

class ImageBaseTask extends AsyncTask<ReadableArray, Void, WritableArray> {
    private final WeakReference<Promise> promiseWeakReference;

    public ImageBaseTask(Promise promise) {
        promiseWeakReference = new WeakReference<Promise>(promise);
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to {@link #execute}
     * by the caller of this task.
     * <p>
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     *
     * @param params The parameters of the task.
     * @return A result, defined by the subclass of this task.
     * @see #onPreExecute()
     * @see #onPostExecute
     * @see #publishProgress
     */
    @Override
    protected WritableArray doInBackground(ReadableArray... params) {
        WritableArray fileList = Arguments.createArray();
        for (int i = 0; i < params[0].size(); i++) {
            ReadableMap fileInfo = params[0].getMap(i);
            String filePath = fileInfo.getString("filePath");
            double imageWidth = -1;
            double imageHeight = -1;
            int scale = -1;
            if (fileInfo.hasKey("width"))
                imageWidth = fileInfo.getDouble("width");
            if (fileInfo.hasKey("height"))
                imageWidth = fileInfo.getDouble("height");
            if (fileInfo.hasKey("scale"))
                scale = (int) fileInfo.getDouble("scale") * 100;
            WritableMap returnFileInfo = Arguments.createMap();
            returnFileInfo.putString("filePath", filePath);
            returnFileInfo.putString("imageData", LocalUtil.getPirBase(filePath, imageWidth, imageHeight, scale));
            fileList.pushMap(returnFileInfo);
        }
        return fileList;
    }

    @Override
    protected void onPostExecute(WritableArray fileBase) {
        if (promiseWeakReference != null && fileBase != null) {
            final Promise promise = promiseWeakReference.get();
            promise.resolve(fileBase);
        }
    }
}
